package net.documentshare.docu.video;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.documentshare.docu.DocuBean;
import net.documentshare.docu.DocuUtils;
import net.documentshare.documentconfig.DocumentConfigMgr;
import net.documentshare.documentconfig.StorageBean;
import net.documentshare.utils.IOUtils;

public class VideoViewerServlet extends HttpServlet {

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		HttpServletResponse response = resp;
		OutputStream outp = null;
		InputStream in = null;
		try {
			outp = response.getOutputStream();
			DocuBean docuBean = DocuUtils.applicationModule.getBean(DocuBean.class, req.getParameter("docuId"));
			if (docuBean != null) {
				final StorageBean storageBean = DocumentConfigMgr.getDocuMgr().getStorageMap().get(docuBean.getPath2());
				if (storageBean != null) {
					in = storageBean.getInputStream(DocuUtils.getDatabase(docuBean.getUserId()) + docuBean.getFileName());
				}
			}
			// LOGGER.info("获取文档!");	
			response.setContentLength(in.available());
			byte[] b = new byte[1024];
			int i = 0;
			while ((i = in.read(b)) > 0) {
				outp.write(b, 0, i);
				outp.flush();
			}
			outp.flush();

		} catch (Exception ex) {
			response.setStatus(404);
			ex.printStackTrace();
		} finally {
			if (in != null) {
				IOUtils.closeIO(in);
				in = null;
			}
			if (outp != null) {
				IOUtils.closeIO(outp);
				outp = null;
			}
		}
	}

	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		doGet(req, resp);
	}
}
